package com.zchi.customizeAuthentication.security.smsCode;

import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 短信验证码过滤器，验证短信登录验证码是否正确
 * @Author 张弛
 * @Datee 2021/7/4
 * @Version 1.0
 **/
@Setter
public class SmsValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        boolean action = false;
        String url = "/authentication/smsLogin";
        if (pathMatcher.match(url, httpServletRequest.getRequestURI())) {
            action = true;
        }

        if (action) {

            try {
                validate(new ServletWebRequest(httpServletRequest));
            } catch (ValidateCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }

        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {

        // todo 获取验证码，现在先写死，之后改成从session或者redis中获取
        String codeInSession = "f123";

        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if(codeInSession == null){
            throw new ValidateCodeException("验证码不存在");
        }

        // todo 验证码是否过期

        if(!StringUtils.equals(codeInSession, codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }

        // todo 使用完这个验证码就删除
    }

    public void setFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }
}
